<script>
import { mapMutations } from 'vuex'
import config from './config'
export default {
  data() {
    return {
      wsConnectingLock: false
    }
  },
  methods: {
    ...mapMutations(['login']),
    openWebSocket(accessToken) {
      const that = this
      if (that.wsConnectingLock) {
        return
      }
      that.wsConnectingLock = true
      uni.connectSocket({
        url: that.$api.config.baseWsUrl + '/' + accessToken,
        method: 'POST',
        success() {
          console.log('WebSocket 连接成功！')
          uni.onSocketMessage((res) => {
            const o = JSON.parse(res.data)
            console.log('收到服务器内容：')
            console.log(o)
            if (o.code === 2) {
              // 数据点更新
              that.$store.commit('updateDeviceDataSingle', o.dataPoint)
            } else if (o.code === 3) {
              that.$store.commit('updateDeviceData', o.snapshots)
            }
          })
          uni.onSocketClose(function(res) {
            console.log('WebSocket 已关闭！')
            console.log(res)
          })
        },
        fail() {
          that.wsConnectingLock = false
        }
      })
    },
    checkLogin(userInfo, callback) {
      uni.request({
        url: config.baseUrl + '/api/user/checkLogin',
        header: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
          'ACCESSTOKEN': userInfo.accessToken
        },
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200) {
            if (res.data.errno === 200) {
              // 此登录状态还有效
              callback()
            }
          }
        }
      })
    }
  },
  onLaunch: function() {
    console.log('App Launch')
    // 首次启动时，从本地缓存中
    const that = this
    const userInfo = uni.getStorageSync('userInfo') || ''
    if (userInfo.id) {
      // 更新登陆状态
      that.checkLogin(userInfo, () => {
        that.login(userInfo)
        that.openWebSocket(userInfo.accessToken)
      })
    }
  },
  onShow: function() {
    // 连接WS
    console.log('App Show')
    const that = this
    const userInfo = uni.getStorageSync('userInfo') || ''
    if (userInfo.id) {
      // 更新登陆状态
      that.checkLogin(userInfo, () => {
        that.openWebSocket(userInfo.accessToken)
      })
    }
  },
  onHide: function() {
    // 断开WS连接
    console.log('App Hide')
    const that = this
    uni.closeSocket()
    that.wsConnectingLock = false
  }
}
</script>

<style>
    /* #ifndef APP-PLUS-NVUE */
    /* uni.css - 通用组件、模板样式库，可以当作一套ui库应用 */
    @import './common/uni.css';

    /* 以下样式用于 hello uni-app 演示所需 */
    page {
        height: 100%;
    }
    /* #endif*/

    .app-content {
        background: #2D335A;
        background-image: linear-gradient(45deg,#4D395C,#253155);
        width: 100%;
        height: 100%
    }

    /* #ifdef MP-360 */
    ::-webkit-scrollbar {width: 4px; height: 4px; background-color: transparent;}
    ::-webkit-scrollbar-track {background-color: transparent;}
    ::-webkit-scrollbar-thumb {background-color: #ddd;}
    ::-webkit-scrollbar-thumb:hover {background-color: #ccc;}
    ::-webkit-scrollbar-thumb:active {background-color: #bbb;}
    ::-webkit-scrollbar-corner {background: #ffffff;}
    /* #endif*/
</style>
